var connect = require('connect');
var ejs = require('ejs');
var fs = require('fs');
var socketio = require('socket.io');

var rooms = [];

// create and run web server
var server = connect.createServer();
server.use(connect.router(function(app) {
	// GET - /
	app.get('/', function(request, response) {
		fs.readFile('./resources/lobby.html', function(error, data) {
			response.writeHead(200, {'Content-Type': 'text/html'});
			response.end(data);
		});	
	});
	
	// GET - /canvas/:room
	app.get('/canvas/:room', function(request, response) {
		fs.readFile('./resources/canvas.html', 'utf8', function(error, data) {
			response.writeHead(200, {'Content-Type': 'text/html'});
			response.end(ejs.render(data, {
				room: request.params.room
			}));
		});
	});
	
	// GET - /rooms
	app.get('/rooms', function(request, response) {
		response.writeHead(200, {'Content-Type': 'application/json'});
		response.end(JSON.stringify(rooms));
	});
}));

server.use(connect.static(__dirname + '/resources'));

server.listen(52273, function() {
	console.log('Server running at http://localhost:52273');
});

var io = socketio.listen(server);
io.set('log level', 2);
io.sockets.on('connection', function(socket) {
	socket.on('join', function(data) {
		socket.join(data);
		socket.set('room', data);
	});
	
	socket.on('draw', function(data) {
		socket.get('room', function(error, room) {
			io.sockets['in'](room).emit('line', data);
		});
	});
	
	socket.on('addroom', function(data) {
		console.log('addroom: ' + data);
		rooms.push(data);
		io.sockets.emit('addroom', data);
	});
});